package cn.wolfcode.crm.realm;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.service.IEmployeeService;
import cn.wolfcode.crm.service.IPermissionService;
import cn.wolfcode.crm.service.IRoleService;
import lombok.Setter;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.List;

//自定义realm类
public class EmployeeRealm extends AuthorizingRealm {

    public String getName() {
        return "EmployeeRealm";
    }

    @Setter
    private IEmployeeService employeeService;
    @Setter
    private IRoleService roleService;
    @Setter
    private IPermissionService permissionService;
    //认证
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取当前用户在页面的输入信息
        String username = (String) authenticationToken.getPrincipal();
        //从数据库中查询
        Employee employee = employeeService.getEmployeeByUsername(username);
        //判断
        if (employee ==null){
            return null;
        }
        //将当前用户信息进行保存
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(employee,employee.getPassword(),getName());
        return info;
    }
    //授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {

        //获取当前登录的用户信息
        Employee currentUser = (Employee) principal.getPrimaryPrincipal();

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //如果是管理员拥有所有的权限
        if (currentUser.isAdmin()){

            //如果当前用户是管理员
            //拿到当前用户所拥有的角色
            List<Role>roles = (List<Role>) roleService.list();
            for (Role role : roles) {
                //添加角色
                info.addRole(role.getSn());
            }
            //设置权限
            info.addStringPermission("*:*");
        }
        //这里表示不是管理员
        //通过当前用户的id来获取该用户所拥有的角色
        List<String> roles = roleService.getRoleSnByEmployeeId(currentUser.getId());
        //保存角色
        info.addRoles(roles);
        //保存权限
        //通过当前员工的id来获取当前用户的权限
        List<String> permissions = permissionService.getPermissionsByEmployeeId(currentUser.getId());
        //保存权限
        info.addStringPermissions(permissions);

        return info;
    }

}
